c{% extends "./inc/base.html" %}
{% block style %}
<!--<link rel="stylesheet" href="/static/admin/js/zTree/metroStyle/metroStyle.css" type="text/css">-->
<link rel="stylesheet" href="/static/admin/js/zTree/zTreeStyle/zTreeStyle.css" type="text/css">
<link rel="stylesheet" href="/static/admin/js/datepicker/bootstrap-datetimepicker.min.css" type="text/css">
<link rel="stylesheet" href="/static/admin/js/chosen/chosen.css" type="text/css" />
<link rel="stylesheet" href="/static/admin/js/jQuery-Tags-Input/src/jquery.tagsinput.css" type="text/css" />
<link href="/static/admin/js/jquery-ui-1.12.1.custom/jquery-ui.min.css"  rel="stylesheet" type="text/css"/>
<!--<link rel="stylesheet" href="/static/admin/js/uploadify/uploadify.css" type="text/css">-->
<script src="/static/admin/js/jquery.min.js"></script>
<script src="/static/admin/js/chosen/chosen.jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="/static/admin/js/jquery.coolautosuggest.js"></script>
<style type="text/css">
    .tab-content > .tab-pane{
        position: absolute !important;
        clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
        clip: rect(1px,1px,1px,1px);
        display: block;
    }
    .tab-content > .active {
        position:static !important;
        clip: inherit; /* IE6, IE7 */
        clip:inherit;
        display: block;
    }
table tr td{
    font-weight: normal;
    vertical-align: middle !important;
}
    .tabelselet select{display: inline-table;width: inherit}
</style>
{% endblock%}
{% block content %}
<section class="vbox">
    <section id="bjax-target">
        <section class="hbox stretch">
            <!-- side content -->
            {% include "./inc/article_side.html" %}
            <!-- / side content -->
            <section>
                <section class="vbox">
                    <section class="scrollable wrapper">

                        <!-- .breadcrumb -->
                        <ul class="breadcrumb">
                            <li><a href="/admin/article/index"><i class="fa fa-home"></i>网站内容</a></li>
                            {% for nav in breadcrumb%}
                            {% if data.category_id == nav.id %}
                            <li class="active">{{nav.title}} : {{controller.meta_title}}</li>
                            {%else%}
                            <li><a href="/admin/article/index/cate_id/{{nav.id}}"><i class="fa fa-list-ul"></i> {{nav.title}}</a></li>
                            {% endif %}
                            {% endfor %}

                        </ul>
                        <!-- / .breadcrumb -->
                        <div class="row">
                            <div class="col-lg-12"><section class="panel panel-default">
                                <header class="panel-heading text-right bg-light">
                                    <ul class="nav nav-tabs pull-left">
                                        {% for key ,group in model.field_group | parse_config_attr %}
                                        <li {% if 1 == key %} class="active" {% endif %}><a data-toggle="tab" href="#tabl-{{key}}"><i class="fa fa-comments text-muted"></i> {{group}}</a></li>
                                        {% endfor %}
                                    </ul>
                                    <span class="hidden-sm">Left</span>
                                </header>
                                <div class="panel-body">
                                    <form id="ajaxForm" action="/admin/article/update" method="post" class="form-horizontal" data-validate="parsley">
                                    <div class="tab-content">

                                        {% for key ,group in model.field_group | parse_config_attr %}
                                        <div id="tabl-{{key}}" class="tab-pane  {% if 1 == key %}active{% endif %}">
                                            {%if sort and key ==1%}
                                            <input type="hidden" name="sort_id" value="{{data.sort_id}}">
                                            <div class="form-group">
                                                <label  class="col-sm-2 control-label">
                                                    分类
                                                </label>
                                                <div class="col-sm-10">
                                                    <div class="row">
                                                        <div class="col-md-10">
                                                            <div class="btn-group" >
                                                                {%for val in sort.types%}
                                                                <a href="/admin/article/edit/id/{{data.id}}/model/{{data.model_id}}/cate_id/{{data.category_id}}/sortid/{{val.enable}}" class="btn btn-sm btn-default {%if data.sort_id == val.enable%}active{%endif%}">
                                                                    {{val.name}}
                                                                </a>
                                                                {%endfor%}

                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            {%for val in typevar%}
                                            {%if val.available==1%}
                                            <div class="form-group">
                                                <label  class="col-sm-2 control-label">
                                                    {{val.option.title}}
                                                </label>
                                                <div class="col-sm-10">
                                                    <div class="row">

                                                            {%if val.option.type == 'select'%}
                                                        <div class="col-md-10">
                                                            <input type="hidden" name="sortid_{{val.option.identifier}}" value="{{val.option.value}}" {% if val.required == 1 %}data-required="true"{%endif%}>
                                                            <label id="info_{{val.option.identifier}}"  class="checkbox-inline i-checks" >{{val.option.rules.choices[val.option.value]|default("请选择",true)}}</label>
                                                            <span id="sortid_{{val.option.identifier}}" class="tabelselet"></span>
                                                            <a href="#" id="edit_{{val.option.identifier}}" class="checkbox-inline i-checks text-info">修改</a>

                                                            <script>



                                                                $(function () {
                                                                    function getShowTimes(string,indexChar){
                                                                        //返回一个字符在字符串中出现的次数
                                                                        return (string.split(indexChar).length-1);
                                                                    }

                                                                    var jsonObj ={{val.option.rules.choices|jsonToStr|safe}};
                                                                    /*递归实现获取无级树数据并生成DOM结构*/
                                                                    var jValue;
                                                                    //alert(getShowTimes("4.2.1","4.3"));
                                                                    var forTree = function(o){
                                                                        jValue ='<select class="form-control">';
                                                                        jValue +='<option value=""  >请选择</option>';
                                                                        for(var item in jsonObj){
                                                                            if(item.indexOf(".")<0){
                                                                                jValue +='<option value='+ item +'>'+ jsonObj[item] +'</option>';
                                                                            }
                                                                        }
                                                                        jValue += "</select>";
                                                                        return jValue;
                                                                    }
                                                                    var subTree = function(jsonObj,item){
                                                                        var arr =[];
                                                                        for(var item2 in jsonObj){
                                                                            let vvv = item+".";
                                                                            let count = getShowTimes(vvv,".")
                                                                            if(item2.indexOf(vvv)==0 && getShowTimes(item2,".")==count ){
                                                                                var htm = '<option value='+ item2 +'>'+ jsonObj[item2] +'</option>';
                                                                                arr.push(htm);
                                                                                //subTree(jsonObj,item2);
                                                                            }
                                                                        }
                                                                        if(arr.length>0){
                                                                            var str = "";
                                                                            str +='<select class="form-control">';
                                                                            str +='<option value="">请选择</option>';
                                                                            str += arr.join("")
                                                                            str += "</select>";
                                                                            return str;
                                                                        }

                                                                    }
                                                                    $(document).on("change","#sortid_{{val.option.identifier}} select",function () {
                                                                        var val = $(this).find("option:selected").val();
                                                                        var text = $(this).find("option:selected").text();
                                                                        var info;
                                                                        if(val){
                                                                            info = "你的选择: <b class='text-info'>" + text+"</b>";
                                                                        }else {
                                                                            info =text;
                                                                        }
                                                                        $(this).nextAll().remove();
                                                                        $(this).after(subTree(jsonObj, val));
                                                                        $('input[name="sortid_{{val.option.identifier}}"]').val(val);
                                                                        $("#info_{{val.option.identifier}}").html(info)
                                                                    })
                                                                    $(document).on("click","#edit_{{val.option.identifier}}",function (e) {
                                                                        e.preventDefault();

                                                                        $("#sortid_{{val.option.identifier}}").html(forTree(jsonObj));
                                                                    })
                                                                    //

                                                                })
                                                            </script>

                                                        </div>
                                                        {#
                                                        <div class="col-md-3">
                                                            <select class="form-control " name="sortid_{{val.option.identifier}}" {% if val.required == 1 %}data-required="true"{%endif%}>
                                                                <option value=" "  >请选择</option>
                                                                {% for k ,v in val.option.rules.choices %}
                                                                <option value="{{k}}" {% if val.option.value == k %}selected{%endif%}>[{{k}}] {{v}}</option>
                                                                {% endfor %}
                                                            </select>
                                                            </div>
                                                        #}
                                                        {% elif val.option.type == 'number' or val.option.type == 'range'%}
                                                        <div class="col-md-2">
                                                            <input type="number" class="form-control " name="sortid_{{val.option.identifier}}" value="{{val.option.value}}"  {% if val.required == 1 %}data-required="true"{%endif%}>
                                                        </div>
                                                        {% elif val.option.type == 'textarea' %}
                                                        <div class="col-md-8">
                                                            <textarea class="form-control" name="sortid_{{val.option.identifier}}"  {% if val.required == 1 %}data-required="true"{%endif%}  {% if val.option.rules.rowsize %} rows="{{val.option.rules.rowsize}}" {% endif %}>{{val.option.value}}</textarea>
                                                        </div>
                                                        {% elif val.option.type == 'radio' %}
                                                        <div class="col-md-8">
                                                            {% for k ,v in val.option.rules.choices %}
                                                            <label class="radio-inline i-checks">
                                                                <input type="radio" value="{{k}}" name="sortid_{{val.option.identifier}}" {% if val.option.value == k %}checked{%endif%} ><i></i> {{v}}
                                                            </label>
                                                            {% endfor %}
                                                        </div>
                                                        {% elif val.option.type == 'checkbox' %}
                                                        <div class="col-md-8">
                                                            <input class="hide" type="checkbox" value="0" name="sortid_{{val.option.identifier}}" checked>
                                                            {% for k ,v in val.option.rules.choices %}
                                                            <label class="checkbox-inline i-checks">
                                                                <input type="checkbox" value="{{k}}" name="sortid_{{val.option.identifier}}" {% if k|in_Array(val.option.value|strToJson)  %}checked{%endif%}><i></i> {{v}}
                                                            </label>
                                                            {% endfor %}
                                                        </div>
                                                        {% elif val.option.type == 'calendar' %}
                                                        <div class="col-md-3">
                                                            <input type="text" name="sortid_{{val.option.identifier}}" class="form-control date" value="{{val.option.value}}" data-type="dateIso" placeholder="YYYY-MM-DD" {% if val.required == 1 %}data-required="true"{%endif%}/>
                                                        </div>
                                                        {%elif val.option.type == 'email'%}
                                                        <div class="col-md-3">
                                                            <input type="text" name="sortid_{{val.option.identifier}}" class="form-control" value="{{val.option.value}}" data-type="email" {% if val.required == 1 %}data-required="true"{%endif%}>
                                                        </div>
                                                        {%elif val.option.type == "image"%}
                                                        <div class="col-sm-10">
                                                            <input type="hidden" name="sortid_{{val.option.identifier}}" id="sortid_{{val.option.identifier}}" value="{{val.option.value}}"/>
                                                            <div id="fileList_sortid_{{val.option.identifier}}" class="uploader-list"></div>
                                                            <div id="filePicker_sortid_{{val.option.identifier}}">选择图片</div>
                                                            <script type="text/javascript">
                                                                $list_sortid_{{val.option.identifier}} = $('#fileList_sortid_{{val.option.identifier}}'),
                                                                        // 优化retina, 在retina下这个值是2
                                                                        ratio_sortid_{{val.option.identifier}} = window.devicePixelRatio || 1,

                                                                        // 缩略图大小
                                                                        thumbnailWidth_sortid_{{val.option.identifier}} = 100 * ratio_sortid_{{val.option.identifier}},
                                                                thumbnailHeight_sortid_{{val.option.identifier}} = 100 * ratio_sortid_{{val.option.identifier}},

                                                                // Web Uploader实例
                                                                uploader_sortid_{{val.option.identifier}};

                                                                // 初始化Web Uploader
                                                                // 初始化Web Uploader
                                                                var uploader_sortid_{{val.option.identifier}} = WebUploader.create({
                                                                    // 选完文件后，是否自动上传。
                                                                    auto: true,
                                                                    // swf文件路径
                                                                    swf: '/static/admin/js/webuploader/Uploader.swf',
                                                                    // 文件接收服务端。
                                                                    server: '/ext/attachment/adminfile/uploadpic',
                                                                    // 选择文件的按钮。可选。
                                                                    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                                                                    pick: {
                                                                        id:'#filePicker_sortid_{{val.option.identifier}}',
                                                                        multiple: false
                                                                    },
                                                                    // 只允许选择图片文件。
                                                                    accept: {
                                                                        title: 'Images',
                                                                        extensions: 'gif,jpg,jpeg,bmp,png',
                                                                        mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif,image/bmp'
                                                                    }
                                                                });
                                                                //当有图片时加载图片
                                                                var cover_id="{{val.option.value}}";
                                                                console.log(cover_id);
                                                                if(cover_id != 0){
                                                                    var picurl = "{{val.option.value|get_pic('m=0,h=110')}}"
                                                                    var $li = $(
                                                                                    '<div id="' + cover_id + '" class="file-item thumbnail ">' +
                                                                                    '<img src="'+picurl+'">' +
                                                                                    '</div>'
                                                                            ),
                                                                            $img = $li.find('img');

                                                                    $list_{{field.name}}.html( $li );
                                                                }
                                                                // 当有文件添加进来的时候
                                                                uploader_sortid_{{val.option.identifier}}.on( 'fileQueued', function( file ) {
                                                                    var $li = $(
                                                                                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                                                                                    '<img>' +
                                                                                    '<div class="info">' + file.name + '</div>' +
                                                                                    '</div>'
                                                                            ),
                                                                            $img = $li.find('img');

                                                                    $list_sortid_{{val.option.identifier}}.html( $li );

                                                                    // 创建缩略图
                                                                    uploader_sortid_{{val.option.identifier}}.makeThumb( file, function( error, src ) {
                                                                        if ( error ) {
                                                                            $img.replaceWith('<span>不能预览</span>');
                                                                            return;
                                                                        }

                                                                        $img.attr( 'src', src );
                                                                    }, thumbnailWidth_sortid_{{val.option.identifier}}, thumbnailHeight_sortid_{{val.option.identifier}} );
                                                                });

                                                                // 文件上传过程中创建进度条实时显示。
                                                                uploader_sortid_{{val.option.identifier}}.on( 'uploadProgress', function( file, percentage ) {

                                                                    var $li = $( '#'+file.id ),
                                                                            $percent = $li.find('.progress span');

                                                                    // 避免重复创建
                                                                    if ( !$percent.length ) {
                                                                        $percent = $('<p class="progress"><span></span></p>')
                                                                                .appendTo( $li )
                                                                                .find('span');
                                                                    }

                                                                    $percent.css( 'width', percentage * 100 + '%' );
                                                                });

                                                                // 文件上传成功，给item添加成功class, 用样式标记上传成功。
                                                                uploader_sortid_{{val.option.identifier}}.on( 'uploadSuccess', function( file,res ) {
                                                                    $( '#'+file.id ).addClass('upload-state-done');
                                                                    $("#sortid_{{val.option.identifier}}").val(res);
                                                                });

                                                                // 文件上传失败，现实上传出错。
                                                                uploader_sortid_{{val.option.identifier}}.on( 'uploadError', function( file ) {
                                                                    var $li = $( '#'+file.id ),
                                                                            $error = $li.find('div.error');

                                                                    // 避免重复创建
                                                                    if ( !$error.length ) {
                                                                        $error = $('<div class="error"></div>').appendTo( $li );
                                                                    }

                                                                    $error.text('上传失败');
                                                                });

                                                                // 完成上传完了，成功或者失败，先删除进度条。
                                                                uploader_sortid_{{val.option.identifier}}.on( 'uploadComplete', function( file ) {
                                                                    $( '#'+file.id ).find('.progress').remove();
                                                                });
                                                            </script>
                                                        </div>
                                                        {%elif val.option.type == "url"%}
                                                        <div class="col-md-6">
                                                            <input type="text" name="sortid_{{val.option.identifier}}" data-type="url" value="{{val.option.value}}"  {% if val.required == 1 %}data-required="true"{%endif%} class="form-control" placeholder="">
                                                        </div>
                                                        {%else%}
                                                        <div class="col-md-8">
                                                            <input type="text" class="form-control " name="sortid_{{val.option.identifier}}" value="{{val.option.value}}"  {% if val.required == 1 %}data-required="true"{%endif%}>
                                                        </div>
                                                            {%endif%}
                                                        </div>
                                                    </div>
                                                </div>
                                            {%endif%}
                                            {%endfor%}
                                            <div class="line line-dashed b-b line-lg pull-in"></div>
                                            {%endif%}
                                            {% if groups and key==1 %}
                                            {#  <div class="form-group">
                                                <label  class="col-sm-2 control-label">
                                                    分组
                                                </label>
                                                <div class="row">
                                                    <div class="col-md-3">
                                                        <select class="form-control " name="group_id">
                                                            <option value="0" {% if data.group_id == k%} selected {%endif%}>不分组</option>
                                                            {% for k ,v in groups %}
                                                            <option value="{{k}}" {% if data.group_id == k%} selected {%endif%}>{{v}}</option>
                                                            {% endfor %}
                                                        </select>
                                                    </div>
                                                </div>
                                            </div> #}
                                            {% endif%}
                                            {% for field in fields[key] %}
                                            {% if field.is_show == 1 or field.is_show == 2 %}
                                            <div class="form-group">

                                                    {% if field.type == "editor" %}
                                                    <div class="col-sm-12">
                                                    {% else%}
                                                    <label class="col-sm-2 control-label">{{field.title}}</label>
                                                    <div class="col-sm-10">
                                                    {%endif%}

                                                    <div class="row">
                                                        {% if field.type == "num" %}
                                                        <div class="col-md-2">
                                                            <input type="text" class="form-control  " name="{{field.name}}" value="{{data[field.name]}}"  >
                                                        </div>
                                                        {% elif field.type == "string" %}
                                                        <div class="col-md-10">
                                                            <input type="text" class="form-control  " name="{{field.name}}" value="{{data[field.name]}}" >
                                                        </div>
                                                        {% elif field.type == "textarea" %}
                                                        <div class="col-md-10">
                                                            <textarea name="{{field.name}}" class="form-control">{{data[field.name]}}</textarea>
                                                        </div>
                                                        {% elif field.type == "date" %}
                                                        <div class="col-md-3">
                                                            <input type="text" name="date|||{{field.name}}" class="form-control date" value="{%if data[field.name]==0%}{%else%}{{data[field.name]|moment('YYYY-MM-DD')}}{%endif%}" placeholder="请选择日期" />
                                                        </div>
                                                        {% elif field.type == "datetime" %}
                                                        <div class="col-md-3">
                                                            <input type="text" name="date|||{{field.name}}" class="form-control time" value="{%if data[field.name]==0%}{%else%}{{data[field.name]|moment('YYYY-MM-DD HH:mm')}}{%endif%}" placeholder="请选择时间" />
                                                        </div>
                                                        {% elif field.type == "keyword" %}
                                                        <div class="col-md-10">
                                                            <input type="text" class="form-control" id="{{field.name}}" name="{{field.name}}" value="{{data[field.name]}}" >
                                                        </div>
                                                        <script>
                                                            $(function () {
                                                                $('#{{field.name}}').tagsInput({
                                                                    autocomplete_url:'/admin/public/getkeyword',
                                                                    autocomplete:{selectFirst:true,autoFill:true},
                                                                    width:'auto',
                                                                    height:'43px',
                                                                    defaultText:'添加标签'
                                                                });
                                                            })
                                                        </script>
                                                        {%elif field.type == 'relation'%}
                                                        {%set relext = field.extra|parse_config_attr%}
                                                        <div class="col-md-3">
                                                            <input type="hidden" name="{{field.name}}" value="{{data[field.name]}}" id="{{field.name}}">
                                                            <input type="text" class="form-control  " id="{{field.name}}_show" name="{{field.name}}_show" value="{{data[field.name]|get_relation(relext.model,relext.id,relext.val)}}" />

                                                            <script language="javascript" type="text/javascript">
                                                                $("#{{field.name}}_show").coolautosuggest({
                                                                    url:"/admin/public/getrelation/?model={{relext.model}}&id={{relext.id}}&val={{relext.val}}&key=",
                                                                    onSelected:function(result){

                                                                        // Check if the result is not null
                                                                        if(result!=null){
                                                                            $("#{{field.name}}").val(result.id); // Get the ID field
                                                                        }
                                                                        else{
                                                                            $("#{{field.name}}").val(""); // Empty the ID field

                                                                        }
                                                                    }
                                                                });
                                                            </script>
                                                        </div>
                 {% elif field.type == "freight" %}
                <div class="col-md-5">
                    <input type="hidden" name="{{field.name}}" value='{{data[field.name]}}' id="{{field.name}}"/>
                    {% set freight = data[field.name]|strToJson %}
                   <table  class="table table-bordered b-t b-light m-b-none">
                        <tr><td>
                    <div class="radio i-checks">
                          <label>
                            <input type="radio" {%if freight.type == 0%}checked=""{%endif%} value="0" id="js-unified-postage" name="{{field.name}}_radio">
                            <i></i>
                            统一运费 
                          </label>
                         
                        </div>
                        </td>
                        <td>
                       <div class="radio i-checks">
                          <label>
                            <input type="radio" {%if freight.type == 1%}checked=""{%endif%} value="1" id="js-use-delivery" name="{{field.name}}_radio">
                            <i></i>
                            运费模板
                          </label>
                        </div>
                         
                        </td></tr>
                        <tr><td colspan="2">
                            <div class="radio-tab1 {%if freight.type == 1%}hide{%endif%}">
                       <div class="input-group">
                          <span class="input-group-addon">￥</span>
                          <input type="text" class="form-control" style="width:100px" value="{%if freight.type == 0%}{{freight.val}}{%else%}0{%endif%}" id="js-postage">
                        </div>
                            </div>
                            <div class="radio-tab2 {%if freight.type == 0%}hide{%endif%} ">
                          <select style="width:260px" data-placeholder="请选择运费模板" class="chosen-select1" id="js-delivery-template">
                                <option value=""></option>
                                <option value="1" {%if freight.val == 1 and freight.type==1 %} selected="selected"{%endif%}>测试运费模板1</option>
                                <option value="2" {%if freight.val == 2 and freight.type==1 %} selected="selected"{%endif%}>测试运费模板2</option>
                        </select>
                            </div>
                        </td>
                        </tr>
                            </table>
                            <script>
                             $.each($("[name='{{field.name}}_radio']"),function(){
                                 
                                 $(this).click(function(){
                                     var id = $(this).val();
                                     var val;
                                     if(0 == id){
                                      val = $("#js-postage").val()
                                      $(".radio-tab1").removeClass('hide');
                                      $(".radio-tab2").addClass('hide');
                                     }else{
                                      val =$("#js-delivery-template  option:selected").val();
                                       $(".radio-tab1").addClass('hide');
                                      $(".radio-tab2").removeClass('hide');   
                                     }
                                     var o = {"type":id,"val":val};
                                     $("#{{field.name}}").val(JSON.stringify(o));
                                 })
                                 
                             })
                             $("#js-postage").on("focus",function(){
                                  val = $("#js-postage").val()
                                  var o = {"type":0,"val":val};
                                 $("#{{field.name}}").val(JSON.stringify(o));
                             })
                             $("#js-postage").on("change",function(){
                                 val = $("#js-postage").val()
                                  var o = {"type":0,"val":val};
                                 $("#{{field.name}}").val(JSON.stringify(o));
                             })
                             
                              $(".chosen-select1").chosen().change(function(){
                                 //$("#js-unified-postage").attr("checked",false);
                                
                                 val =$("#js-delivery-template  option:selected").val();
                                 var o = {"type":1,"val":val};
                                 $("#{{field.name}}").val(JSON.stringify(o));
                             })
                            </script>
                </div>
                  {% elif field.type == "suk" %}
                <div class="col-md-10">
                    <input type="hidden" name="{{field.name}}" class="form-control" value="{{data[field.name]}}" id="{{field.name}}" />
                    <section class="panel panel-default">
                    <header class="panel-heading {{field.name}}_heading hide"><ul class="nav nav-pills pull-right">
                        <li>
                          <a href="#" class="panel-toggle text-muted"><i class="fa fa-caret-down text-active"></i><i class="fa fa-caret-up text"></i></a>
                        </li>
                      </ul>商品规格</header>
                    <section class="chat-list panel-body {{field.name}}_body hide">
                        {% set pp = data[field.name]|strToJson%}
                        {% set n = 0 %}
                        {% for v in pp.type %}
                         {% set n = n+1 %}
                          <section class="panel panel-default m-b-none " data-id="select-{{n}}">
                                        <header class="panel-heading bg-light no-border">
                                        <div class="clearfix">
                                            <select style="width:260px" class="chosen-select" data-placeholder="请选择规格">
                                                {%for t in tags%}
                                            <option value="{{t.id}}"{%if v == t.name %} selected{%endif%}>{{t.name}}</option>
                                          {%endfor%}
                                            </select>
                                            <a class="btn btn-sm btn-default popover-hide" title=""  data-html="true" data-toggle="popover" data-placement="bottom" data-original-title='<button type="button" class="close pull-right" data-dismiss="popover">&times;</button>添加规格'
                                                data-content="<div class='form-inline'><div class='form-group '><input type='text' placeholder='请输入规格' class='form-control input-sm m-l js-tas-input'></div><a class='btn btn-success btn-sm js-tags ' href='javascript:;'>保存</a></div>">添加规格</a>
                                            {%if n == 1%}<div class="checkbox i-checks checkbox-inline" style="margin-left: 15px"><label><input type="checkbox" name="is_pic" id="js-addImg-function" value="1" {%if pp.is_pic == 1%}checked{%endif%} ><i></i>添加规格图片</label></div>{%endif%}
                                            <a  class="close {{field.name}}_close" id="select-{{n}}" >×</a>
                                        </div>
                                        </header>
                                        <div class="list-group no-radius alt">
                                        <div href="#" class="list-group-item">
                                        <input type="text" class="tags" value="" />
                                        </div>
                                        </div>
                              {%if n == 1%}<div id="upload-img-wrap">
                              {% if pp.is_pic ==1%}
                              {%set size = 0%}
                              {%for pic in pp.data%}

                              <div id="box_{{size}}" class="uplodbox"><input type="hidden" id="cover_id_{{size}}" value="{{pic.pic}}">
                                  <div class="uploader-list" id="fileList_{{size}}"><div class="file-item thumbnail upload-state-done" id="WU_FILE_{{size}}">
                                      <img src="{{pic.pic|get_pic('m=1,w=110,h=110')}}" style="height:100px;width: 100px">
                                      <div class="info">{{pic.name}}</div><div class="atom-close close-modal small js-remove-sku-atom">×</div></div></div>
                                  <div data-id="{{size}}" id="filePicker_{{size}}" class="webuploader-container hide">
                                      <i style="font-size: 36px;margin-top: 15px" class="fa fa-file-image-o"></i><br>{{pic.name}}</div> </div>
                              {%set size=size+1%}
                              {%endfor%}
                              {%endif%}
                          </div>{%endif%}
                                    </section>
                                    {%endfor%}
                    </section>
                    <footer class="panel-footer btn btn-block" id="{{field.name}}_addsuk">
                    <!-- chat form -->
                    <i class="fa fa-plus text"></i> 添加规格项目
                    </footer>
                </section>
                <section class="panel panel-default {{field.name}}_table hide">
                <header class="panel-heading">
                    <ul class="nav nav-pills pull-right">
                        <li>
                          <a href="#" class="panel-toggle text-muted"><i class="fa fa-caret-down text-active"></i><i class="fa fa-caret-up text"></i></a>
                        </li>
                      </ul>
                 规格配置
                </header>
              
                <div class="table-responsive panel-body p-none">
                  <table class="table table-bordered b-t b-light">
                    <thead> </thead>
                    <tbody></tbody>
                  </table>
                </div>
                {#<footer class="panel-footer">
                  <div class="row">
                    <div class="col-sm-10 hidden-xs">
                      批量设置: <a class="btn btn-sm btn-default popover-hide" title=""  data-html="true"
      data-toggle="popover" data-placement="bottom" data-original-title='<button type="button" class="close pull-right" data-dismiss="popover">&times;</button>设置价格' 
      data-content="<div class='form-inline'><div class='form-group '><input type='text' placeholder='请输入价格' id='price-batch-txt' class='form-control input-sm m-l'></div><a class='btn btn-success btn-sm ' id='js-batch-price' href='###'>保存</a></div>">价格</a>
      <a class="btn btn-sm btn-default popover-hide" title=""  data-html="true"
      data-toggle="popover" data-placement="bottom" data-original-title='<button type="button" class="close pull-right" data-dismiss="popover">&times;</button>设置库存' 
      data-content="<div class='form-inline'><div class='form-group '><input type='text' placeholder='请输入库存' id='stock-batch-txt' class='form-control input-sm m-l'></div><a class='btn btn-success btn-sm ' id='js-batch-stock'  href='###'>保存</a></div>">库存</a>
                        <a class="btn btn-sm btn-default popover-hide" title=""  data-html="true"
                           data-toggle="popover" data-placement="bottom" data-original-title='<button type="button" class="close pull-right" data-dismiss="popover">&times;</button>设置重量（件/g）'
                           data-content="<div class='form-inline'><div class='form-group '><input type='text' placeholder='请输入单价商品的重量' id='weight-batch-txt' class='form-control input-sm m-l'></div><a class='btn btn-success btn-sm ' id='js-batch-weight'  href='javascript:;'>保存</a></div>">重量（件/g）</a>
                    </div>
                    
                  </div>
                </footer>#}
              </section>
        <script>
        $(function(){
         var stock_val = '{{data[field.name]|safe}}';
         console.log(stock_val);
         if(stock_val){
             stock_val = JSON.parse(stock_val);
             //console.log(stock_val);

             var arr1=[];
             var nn=0
             $.each(stock_val.data,function(k,v){
                 uploadpic(k,v.name);
                arr1.push(v.name);
                var arr2=[];
                if(v.ch){
                    $.each(v.ch,function(_k,_v){
                       // console.log(_v.name);
                        arr2.push(_v.name);
                        var arr3 = [];
                        if(_v.ch){
                           $.each(_v.ch,function(__k,__v){
                              arr3.push(__v.name); 
                              
                           }) 
                        }
                        if(_k==0 && k==0){
                   $(".tags").eq(2).val(arr3.join(",")); 
                }
                    })
                }
                console.log(arr2);
                if(k==0){
                   $(".tags").eq(1).val(arr2.join(",")); 
                }
             }) 
             $(".tags").eq(0).val(arr1.join(","));

             }
        localStorage.setItem("tagstj",1)
        //初始化规格
         $('.tags').tagsInput({
            width:'auto',
            height:'43px',
            defaultText:'添加规格',
            onChange: function(elem, elem_tags)
                {
                   var dd = $(elem).parent().parent().parent();

                    if($(dd).attr("data-id") == "select-1" && $("#js-addImg-function").attr("checked") && localStorage.getItem("tagstj") !=1){
                        drawPicBox();
                    }

                    drawThead()//绘制表头
                    drawTbody()//绘制表格
                    //当有规格添加时锁定价格和库存
                        $("#present_price").attr("disabled",true);
                    $("input[name='weight']").attr("disabled",true);
                }
            });
            localStorage.removeItem("tagstj")
            //初始化图片
//            if($("#js-addImg-function").attr("checked") ){
//                drawPicBox();
//            }
            cout()
        //批量设置价格
        $(document).on('click',"#js-batch-price",function(){
            var price=$("#price-batch-txt").val();
            $(".sku_price").val(price);
            chandate();
            $('.popover-hide').popover('hide');
        });
         $(document).on('click',"#js-batch-stock",function(){
            var stock=$("#stock-batch-txt").val();
            $(".sku_stock").val(stock);
            chandate();
            $('.popover-hide').popover('hide');
        });
            $(document).on('click',"#js-batch-weight",function(){
                var weight=$("#weight-batch-txt").val();
                $(".sku_weight").val(weight);
                chandate();
                $('.popover-hide').popover('hide');
            });
        //记录添加规格的个数
            function cout(){
                var size = $(".{{field.name}}_body>section").size();
                if(size!=0){
                    $(".{{field.name}}_heading").removeClass("hide");
                    $(".{{field.name}}_body").removeClass("hide");
                    $(".{{field.name}}_table").removeClass("hide");


                }else{
                    $(".{{field.name}}_heading").addClass("hide");
                    $(".{{field.name}}_body").addClass("hide");
                    $(".{{field.name}}_table").addClass("hide");
                    $("#present_price").attr("disabled",false);
                    $("input[name='weight']").attr("disabled",false);
                }
                if(size >= 1){
                    $("#{{field.name}}_addsuk").addClass("hide");
                }else{
                    $("#{{field.name}}_addsuk").removeClass("hide");
                }
            }
        //添加一级规格
       
        $(document).on('change','.chosen-select',function(){
            var val = $('.chosen-select').val();//获取选中的值
            var tex = $('.chosen-select option:selected').text();//选择选择的文字
            drawThead();//绘制表头
            //console.log(val);
            //console.log(tex);
        });
            //绘制第一个规格下面每个标签的图片
            function drawPicBox() {
                var section = $('section.suk_body>section').eq(0);
                var tags = section.find(".tagsinput>span.tag")
                var size =  tags.size();
                var odlediv = $("#upload-img-wrap>div")
                //获取上次的结构
                var arr=[]
                $.each(odlediv,function (k, v) {
                    var obj = {};
                    // var html = '<div class="uplodbox" id="box_'+k+'">'+$(v).html()+'</div>'
                    //console.log(html);
                    var val=$(v).find("input").val();
                    var calss = $(v).find(".webuploader-container").attr("class");
                    var html = $(v).find(".uploader-list").html()
                    obj.val = val;
                    obj.class = calss;
                    obj.html = html;
                    arr.push(obj);
                })
                console.log(arr)
                $.each(tags,function (k, v) {
                    var tagsname = $(v).find("span").text()
                    var pic_upload;

                    if(arr[k]){
                        pic_upload = '<div class="uplodbox" id="box_'+k+'"><input type="hidden" id="cover_id_'+k+'" value="'+arr[k]['val']+'"/>\
                                 <div id="fileList_'+k+'" class="uploader-list">'+arr[k]['html']+'</div>\
                                 <div id="filePicker_'+k+'" data-id="'+k+'" class="'+arr[k]['class']+'"> <i class="fa fa-file-image-o" style="font-size: 36px;margin-top: 15px"></i></br>'+tagsname+'</div></div>'
                        console.log(pic_upload);
                    }else {
                        pic_upload = '<div class="uplodbox" id="box_'+k+'"><input type="hidden" id="cover_id_'+k+'"/>\
                                 <div id="fileList_'+k+'" class="uploader-list"></div>\
                                 <div id="filePicker_'+k+'" data-id="'+k+'"> <i class="fa fa-file-image-o" style="font-size: 36px;margin-top: 15px"></i></br>'+tagsname+'</div></div>'
                    }



                    var imgwrap = section.find("#upload-img-wrap")
                    if(k==0){
                        imgwrap.html(pic_upload);
                    }else {
                        imgwrap.append(pic_upload);
                    }

                    uploadpic(k,tagsname);

                })


            }
            //删除图片
            $(document).on('click',".js-remove-sku-atom",function () {
                //找到父节点清除
                var par = $(this).parents(".uploader-list");
                par.html("");
                //图片从服务器上删除 todo

                //显示上传按钮
                par.next("div.webuploader-container").removeClass("hide");
                //清空图片
                par.prev("input").val("")
                //删除图片后改变数据机构
                chandate();

            })
            //上传图片
            function uploadpic(size,name) {
                $list = $('#fileList_'+size),
                        //console.log($list);
                        // 优化retina, 在retina下这个值是2
                        ratio = window.devicePixelRatio || 1,

                        // 缩略图大小
                        thumbnailWidth = 100 * ratio,
                        thumbnailHeight = 100 * ratio,

                        // Web Uploader实例
                        uploader;

                // 初始化Web Uploader
                // 初始化Web Uploader
                var uploader = WebUploader.create({
                    // 选完文件后，是否自动上传。
                    auto: true,
                    // swf文件路径
                    swf: '/static/admin/js/webuploader/Uploader.swf',
                    // 文件接收服务端。
                    server: '/ext/attachment/adminfile/uploadpic',
                    // 选择文件的按钮。可选。
                    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                    pick: {
                        id:'#filePicker_'+size,
                        multiple: false
                    },
                    // 只允许选择图片文件。
                    accept: {
                        title: 'Images',
                        extensions: 'gif,jpg,jpeg,bmp,png',
                        mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif,image/bmp'
                    }
                });
                // 当有文件添加进来的时候
                uploader.on( 'fileQueued', function( file ) {
                    var $li = $(
                                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                                    '<img>' +
                                    '<div class="info">' + name + '</div>' +
                                    '<div class="atom-close close-modal small js-remove-sku-atom">×</div>'+
                                    '</div>'
                            ),
                            $img = $li.find('img');

                    $('#fileList_'+size).html( $li );
                    $('#filePicker_'+size).addClass("hide");

                    //记录dome
                    // 创建缩略图
                    uploader.makeThumb( file, function( error, src ) {
                        if ( error ) {
                            $img.replaceWith('<span>不能预览</span>');
                            return;
                        }

                        $img.attr( 'src', src );
                    }, thumbnailWidth, thumbnailHeight);
                });

                // 文件上传过程中创建进度条实时显示。
                uploader.on( 'uploadProgress', function( file, percentage ) {

                    var $li = $( '#'+file.id ),
                            $percent = $li.find('.progress span');

                    // 避免重复创建
                    if ( !$percent.length ) {
                        $percent = $('<p class="progress"><span></span></p>')
                                .appendTo( $li )
                                .find('span');
                    }

                    $percent.css( 'width', percentage * 100 + '%' );
                });

                // 文件上传成功，给item添加成功class, 用样式标记上传成功。
                uploader.on( 'uploadSuccess', function( file,res ) {
                    $( '#'+file.id ).addClass('upload-state-done');
                    $("#cover_id_"+size).val(res);
                    //图片上传成功后改变数据
                    chandate();
                });

                // 文件上传失败，现实上传出错。
                uploader.on( 'uploadError', function( file ) {
                    var $li = $( '#'+file.id ),
                            $error = $li.find('div.error');

                    // 避免重复创建
                    if ( !$error.length ) {
                        $error = $('<div class="error"></div>').appendTo( $li );
                    }

                    $error.text('上传失败');
                });

                // 完成上传完了，成功或者失败，先删除进度条。
                uploader.on( 'uploadComplete', function( file ) {
                    $( '#'+file.id ).find('.progress').remove();
                });
            }
            //是否添加图片
            $(document).on("click","#js-addImg-function",function () {

                if($(this).attr("checked")){
                    $(this).attr("checked",false)
                    $("#upload-img-wrap").html("");
                    chandate();
                }else {
                    $(this).attr("checked",true)
                    drawPicBox();
                    chandate();
                }
            })

        //绘制表头
            function drawThead(){
                var arr = $('.chosen-select');
                var narr=[];
                $.each(arr,function(k,v){
                    if($(v).find("option:selected").text().length>0)
                        narr.push($(v).find("option:selected").text());
                });
                //console.log(narr);
                var thHtml = "";
                thHtml += "";
                thHtml += "<tr>";
                for (cSort = 0; cSort <= narr.length - 1; cSort++) {
                    thHtml += '<th class="active">' + narr[cSort] + "</th>";
                }
                thHtml += '<th class="active">修改名称</th><th class="active">编码</th>';
                thHtml += "</tr>";
                thHtml += "";
                $(".{{field.name}}_table").removeClass("hide");
                $(".{{field.name}}_table table thead").html(thHtml);
            }

        //绘制表格
        function drawTbody(){
        $(".{{field.name}}_table").removeClass("hide");
         var type = gettype();
         var narr = getstru();
            var i=0;
            var tbHtml="";
            var tbHtml1="";
            var tbHtml2="";
             var v_sku_price="";
             var v_sku_stock="";
            var v_sku_weight="";
             var v_sku_code="";
            //获取上次chucun的数据；
            var predatas = $("#{{field.name}}").val();
            if(stock_val){
              var predata = stock_val.data;
            }else if(predatas){
              var predata = $.parseJSON(predatas).data;
            }

            $.each(narr,function(k,v){
                if(v.ch){
                    $.each(v.ch,function(_k,_v){
                        if(_v.ch){

                            $.each(_v.ch,function(__k,__v){

                                //输出三级表格
                                //  var v_sku_price,v_sku_stock,v_sku_code;
                                // if(predata){
                                //     if(predata[k]['ch']){
                                //     if(predata[k]['ch'][_k]['ch']){
                                //         console.log(predata[k]['ch'][_k]["ch"][__k])
                                //         var d_=predata[k]['ch'][_k]["ch"][__k];
                                //     if(d_){
                                //     v_sku_price= d_['sku_price'];
                                //     v_sku_stock= d_['sku_stock'];
                                //     v_sku_code= d_['sku_code'];
                                //     }
                                //     }
                                //     }
                                // }
                                try{
                                    // 可能会导致错误的代码
                                    var v_sku_price="";
                                    var v_sku_stock="";
                                    var v_sku_code="";
                                    var d_=predata[k]['ch'][_k]["ch"][__k];
                                    v_sku_price= d_['sku_price']?d_['sku_price']:"";
                                    v_sku_stock= d_['sku_stock']?d_['sku_stock']:"";
                                    v_sku_code= d_['sku_code']?d_['sku_code']:"";
                                    v_sku_weight= d_['sku_weight']?d_['sku_weight']:"";
                                } catch(error){
                                    // 在错误发生时怎么处理
                                }
                                var g = v.ch.length * _v.ch.length;
                                tbHtml += "<tr>";
                                if(i % g == 0){
                                    tbHtml += "<td rowspan="+v.ch.length*_v.ch.length+">" + v.name + "</td>";
                                }
                                if( __k % _v.ch.length == 0){
                                    tbHtml += "<td rowspan="+_v.ch.length+">" + _v.name + "</td>";
                                }
                                tbHtml += "<td rowspan='1'>" + __v.name + "</td>";
                                tbHtml += '<td><input type="text" placeholder="价格" value="'+v_sku_price+'" class="form-control input-sm sku_price"  id="sku_price_'+i+'"></td>\
                        <td><input type="text" placeholder="编码" value="'+v_sku_code+'" class="form-control input-sm sku_code" id="sku_code_'+i+'"></td>';
                                tbHtml += "</tr>";
                                var sku_price="#sku_price_"+i;
                                var sku_stock="#sku_stock_"+i;
                                var sku_code="#sku_code_"+i;
                                var sku_weight="#sku_weight_"+i;
                                __v.sku_weight=$(sku_weight).val();
                                __v.sku_price=$(sku_price).val();
                                __v.sku_stock=$(sku_stock).val();
                                __v.sku_code=$(sku_code).val();
                                i=i+1;
                            })
                        }else{
                            //输出二级表格
                            // var v_sku_price,v_sku_stock,v_sku_code;

                            // if(predata){
                            //     if(predata[k]['ch']){
                            //         console.log(predata[k]["ch"][_k])
                            //         var d_=predata[k]["ch"][_k];
                            //     if(d_){
                            //     v_sku_price= d_['sku_price'];
                            //     v_sku_stock= d_['sku_stock'];
                            //     v_sku_code= d_['sku_code'];
                            //     }
                            //     }
                            // }
                            try{
                                // 可能会导致错误的代码
                                var d_=predata[k]["ch"][_k];
                                v_sku_price= d_['sku_price']?d_['sku_price']:"";
                                v_sku_stock= d_['sku_stock']?d_['sku_stock']:"";
                                v_sku_weight= d_['sku_weight']?d_['sku_weight']:"";
                                v_sku_code= d_['sku_code']?d_['sku_code']:"";
                            } catch(error){
                                // 在错误发生时怎么处理
                            }
                            tbHtml += "<tr>";
                            if( _k % v.ch.length == 0){
                                tbHtml += "<td rowspan="+v.ch.length+">" + v.name + "</td>";
                            }
                            tbHtml += "<td rowspan='1'>" + _v.name + "</td>";
                            tbHtml += '<td><input type="text" placeholder="价格" value="'+v_sku_price+'" class="form-control input-sm sku_price"  id="sku_price_'+i+'"></td>\
                        <td><input type="text" placeholder="编码" value="'+v_sku_code+'" class="form-control input-sm sku_code" id="sku_code_'+i+'"></td>';
                            tbHtml += "</tr>";
                            var sku_price="#sku_price_"+i;
                            var sku_stock="#sku_stock_"+i;
                            var sku_weight="#sku_weight_"+i;
                            var sku_code="#sku_code_"+i;
                            _v.sku_price=$(sku_price).val();
                            _v.sku_stock=$(sku_stock).val();
                            _v.sku_weight=$(sku_weight).val();
                            _v.sku_code=$(sku_code).val();
                            i=i+1;
                        }
                    })
                }else{
                    //输出一级表格

                    if(predata){
                        if(predata[k]){
                          //console.log(predata[k]['sku_price'] != null)
                          v_sku_price= predata[k]['sku_price'] ? predata[k]['sku_price']:"";
                          v_sku_stock= predata[k]['sku_stock'] ? predata[k]['sku_stock']:"";
                          v_sku_weight= predata[k]['sku_weight'] ? predata[k]['sku_weight']:"";
                          v_sku_code= predata[k]['sku_code'] ? predata[k]['sku_code']:"";
                        } else {
                          v_sku_code = '';
                        }
                    }
                    tbHtml += "<tr>";
                    tbHtml += "<td rowspan='1'>" + v.name + "</td>";
                    tbHtml += '<td><input type="text" placeholder="修改名称" value="'+v.name+'" class="form-control input-sm sku_price"  id="sku_price_'+i+'"></td>';
                    // tbHtml += '<td><select style="min-width: 150px" class="form-control input-sm sku_code nc-select" placeholder="编码1" id="sku_code_'+i+'"><option value="'+v_sku_code+'">'+v_sku_code+'</option></select></td>';
                    tbHtml += '<td><input disabled type="text" placeholder="编码" value="'+v_sku_code+'" class="form-control input-sm sku_code"  id="sku_code_'+i+'"></td>';
                    tbHtml += "</tr>";
                    var sku_price="#sku_price_"+i;
                    var sku_stock="#sku_stock_"+i;
                    var sku_weight="#sku_weight_"+i;
                    var sku_code="#sku_code_"+i;

                    v.sku_price=$(sku_price).val();
                    v.sku_stock=$(sku_stock).val();
                    v.sku_weight=$(sku_weight).val();
                    v.sku_code=$(sku_code).val();
                    i=i+1;
                }
            })
                //console.log(tbHtml1);

            $(".{{field.name}}_table table tbody").html(tbHtml);
            //拼装储存数据
            var {{field.name}}_info={
                "type":type,
                "data":narr,
                "is_pic":$("#js-addImg-function:checked").val()?$("#js-addImg-function:checked").val():0
            }
            if(type.length>0){
                $("#{{field.name}}").val(JSON.stringify({{field.name}}_info));
            }else {
                $("#{{field.name}}").val("");
            }

            $(".nc-select").chosen({ placeholder_text: "请选择"});
                                                                }
            // 储存数据
            $(document).on('change','.sku_price,.sku_stock,.sku_code,.sku_weight',function(){
                chandate();
            })

            function chandate(){
                var type = gettype();
                var narr = getstru();
                localStorage.setItem('$narr', JSON.stringify(narr));

                var ntr = $(".suk_table").find("tbody>tr");
                var bianli_arr = [];
                $.each(ntr, function(k,v){
                    var _obj = {};
                    _obj.sku_price = $("#sku_price_"+k).val();
                    _obj.sku_stock = $("#sku_stock_"+k).val();
                    _obj.sku_weight  = $("#sku_weight_"+k).val();
                    _obj.sku_code  = $("#sku_code_"+k).val();
                    bianli_arr.push(_obj);
                });
                //console.log(JSON.stringify(bianli_arr));

                function bianli (arr){
                    for(var i = 0; i < arr.length; i++){
                        try{
                            if(arr[i].ch){
                                bianli(arr[i].ch);
                            }else{
                                var sh = bianli_arr.shift();
                                //console.log(sh);
                                //console.log(arr[i]);
                                for(var k in sh){
                                    arr[i][k] = sh[k];
                                }
                            }
                        }catch(e){
                        }
                    }
                    return arr;
                }
                //console.log(JSON.stringify(narr));
                var result = bianli(JSON.parse(localStorage.getItem("$narr")));
                // console.log(JSON.stringify(result));

                //拼装储存数据
                var {{field.name}}_info={
                    "type":type,
                    "data":result,
                    "is_pic":$("#js-addImg-function:checked").val()?$("#js-addImg-function:checked").val():0
                }
                if(type.length>0){
                    $("#{{field.name}}").val(JSON.stringify({{field.name}}_info));
                }else {
                    $("#{{field.name}}").val("");
                }
                //关联价格
                var pricearr=[];
                $.each($(".sku_price"),function(){
                    pricearr.push($(this).val());
                })
                pricearr.sort(function(a,b){
                    return a-b;
                });
                var discount_price = $("#discount_price").val();
                if(discount_price == ""){
                    discount_price =0;
                }
                if(pricearr[pricearr.length-1]==pricearr[0]){
                    $("#present_price").val(pricearr[0]);
                    var p='{"present_price":"'+pricearr[0]+'","discount_price":"'+discount_price+'"}'
                    $("#price").val(p);
                }else{
                    $("#present_price").val(pricearr[0]+"-"+pricearr[pricearr.length-1]);
                    var p ='{"present_price":"'+pricearr[0]+'-'+pricearr[pricearr.length-1]+'","discount_price":"'+discount_price+'"}'
                    $("#price").val(p);
                }
                //关联库存
                var total_stockarr = 0;
                $.each($(".sku_stock"),function(){
                    total_stockarr=Number($(this).val())+total_stockarr;
                })
                $("input[name='total_stock']").val(total_stockarr);
            }
        
       
        //获取类型
        function gettype(){
        var arr = $('.chosen-select');    
        var type=[];
        $.each(arr,function(k,v){
        if($(v).find("option:selected").text().length>0)
        type.push($(v).find("option:selected").text());
        })
        return type;
        }
        //数据机构
        function getstru(){
        var narr=[];
       
        $.each($(".tags"),function(k,v){
        var type = gettype();
        //narr.push($(v).val());
        item=$(v).val().split(",");
        //获取类型
       
            if(item[0].length != 0){
                if(k==0){
                $.each(item,function(n,m){
                    var obj={};
                    obj.name = m;
                    obj.type = type[k]
                    // console.log(obj);
                    obj.pic = $("#cover_id_"+n).val();
                    narr.push(obj);
                })
                    
                }
                    if(k==1){
                    var ch_arr = [];
                    $.each(item,function(nn,mm){
                    //console.log(mm)
                        var _obj = {};
                        _obj.name = mm; 
                        _obj.type = type[k]
                        ch_arr.push(_obj);
                    });
                    for(var i = 0; i < narr.length; i++ ){
                        narr[i].ch = ch_arr;
                    }
                }
                if(k==2){
                    var ch_arr = [];
                    $.each(item,function(nn,mm){
                        //console.log(mm)
                        var _obj = {};
                        _obj.name = mm; 
                        _obj.type = type[k]
                        ch_arr.push(_obj);
                    });
                    for(var i = 0; i < narr.length; i++ ){
                        for(var j = 0; j < narr[i].ch.length; j++ ){
                            var tmp = narr[i].ch;
                            tmp[j].ch = ch_arr; 
                        }
                    }
                }

            }
            
            })
            
            return narr;
        }
            //添加规格
            $("#{{field.name}}_addsuk").click(function(){

                $.ajax({
                    url:"/admin/tags/ajaxgettags",
                    data:{type:1,pid:0,model_id:{{data.model_id}} },
                success:function(res){
                    var size = $(".{{field.name}}_body>section").size()+1;
//第一个规格添加图片
                    var ispic = "";
                    var ispicwrap = '';
                    if(size ==1){
                        ispic = '<div class="checkbox i-checks checkbox-inline" style="margin-left: 15px"><label><input type="checkbox" id="js-addImg-function" value="1"><i></i>添加规格图片</label></div> ';
                        ispicwrap = '<div id="upload-img-wrap"></div>';
                    }

                    var {{field.name}}_select = ""
                    {{field.name}}_select +='<section class="panel panel-default m-b-none" data-id="select-'+size+'">'+
                            '<header class="panel-heading bg-light no-border">'+
                            '<div class="clearfix">'+
                            '<select style="width:260px" class="chosen-select" data-placeholder="请选择规格">'+
                            '<option value=""></option>';
                    $.each(res,function(index,item){
                        {{field.name}}_select += '<option value="'+item.id+'">'+item.name+'</option>'
                    })

                    {{field.name}}_select+=  '</select> <a class="btn btn-sm btn-default popover-hide" title=""  data-html="true" data-toggle="popover" data-placement="bottom" data-original-title=\'<button type="button" class="close pull-right" data-dismiss="popover">&times;</button>添加规格\''+
                            'data-content="<div class=\'form-inline\'><div class=\'form-group \'><input type=\'text\' placeholder=\'请输入规格\' class=\'form-control input-sm m-l js-tas-input\'></div><a class=\'btn btn-success btn-sm js-tags \' href=\'javascript:;\'>保存</a></div>">添加规格</a>'+
                            ispic +
                            '<a class="close {{field.name}}_close" id="select-'+size+'" >×</a>'+
                            '</div>'+
                            '</header>'+
                            '<div class="list-group no-radius alt">'+
                            '<div href="#" class="list-group-item">'+
                            '<input type="text" class="tags" value="" />'+
                            '</div>'+
                            '</div>'+
                            ispicwrap+
                            '</section>';
                    $('.{{field.name}}_body').append({{field.name}}_select);



                    if($(".chosen-select").length){
                        $('.chosen-select').chosen({ placeholder_text: "选择规则"});
                        $('.tags').tagsInput({
                            width:'auto',
                            height:'43px',
                            defaultText:'添加规格',
                            onChange: function(elem, elem_tags)
                            {
                                if(size == 1 && $("#js-addImg-function").attr("checked") ){
                                    drawPicBox();
                                }
                                drawThead()//绘制表头
                                drawTbody()//绘制表格
                                //当有规格添加时锁定价格和库存
                                $("#present_price").attr("disabled",true);
                                $("input[name='weight']").attr("disabled",true);
                            }
                        });
                    }
                    cout();

                    $("[data-toggle=popover]").popover();


                }
            })
            })
            //删除规格
            $(document).on('click',".{{field.name}}_close",function(){
                var select = $(this).attr("id");

                $('[data-id="'+select+'"]').remove();
                $.each($("section.suk_body>section"),function(i,v){
                    i=i+1;

                    $(v).attr("data-id","select-"+i);
                    $(v).find(".{{field.name}}_close").attr("id","select-"+i);
                })
                drawThead()//绘制表头
                drawTbody()//绘制表格
                cout();
            })
            $(document).on('click','.js-tags',function(){
                var section = $(this).parents('section').attr('data-id');
                section = '[data-id='+section+']';
                var input = $(section).find("input.js-tas-input").val();
                if(input.length==0){
                    toastr.error("请填写规格！");
                    return false;
                }
                $.ajax({
                    type:"POST",
                    url:"/admin/tags/ajaxaddtags",
                    data:{name:input,type:1,model_id:{{data.model_id}} },
                success:function(res){
                    if(res.errno==0){
                        $(section).find("select.chosen-select").append("<option value="+res.id+" selected>"+res.name+"</option>");
                        $('.chosen-select').trigger("liszt:updated");
                        $('.popover-hide').popover('hide');
                        toastr.success("添加规格成功！");
                    }else {
                        toastr.error(res.errmsg);
                    }
                }

            })
            })
                                            //关联价格
                                         $(document).on('change','#present_price,#discount_price',function(){
                                              var discount_price;
                                             if($("#discount_price").val()){
                                                 discount_price = $("#discount_price").val()
                                             }else{
                                                 discount_price = 0
                                             }
                                             $("#price").val('{"present_price":"'+$("#present_price").val()+'","discount_price":"'+discount_price+'"}')
                                         })   
                                        })
                                        
                                    </script>
                                    </div>
         {% elif field.type == "price" %}
    <div class="col-md-5">
    <input type="hidden" name="{{field.name}}" value="{{data[field.name]}}" id="price">
    <div class="row">
    <div class="col-md-6">   <div class="input-group ">
    <span class="input-group-addon">￥</span>
    <input type="text" class="form-control" value="{{data[field.name]|get_price('1')}}" id="present_price">
    </div>  </div>
    <div class="col-md-6">  <input type="text" placeholder="原价：¥99.99"  value="{{data[field.name]|get_price('2')}}"  class="form-control" id="discount_price">  </div>  
    </div>         
    </div>
        {% elif field.type == "pics" %}
        <div class="col-md-10">
            {{HOOKS@adminUpPics[field.name]|safe}}
        </div>
    {% elif field.type == "atlas" %}
    <div class="col-md-10">
        {{HOOKS@adminAtlas[field.name]|safe}}
    </div>
    {% elif field.type == "bool" %}
    <div class="col-md-4">
        <select class="form-control " name="{{field.name}}">
            {% for k ,v in field.extra|parse_config_attr %}
            <option value="{{k}}" {% if data[field.name] == k%} selected {%endif%}>{{v}}</option>
            {% endfor %}
        </select>
    </div>
    {% elif field.type == "select" %}
    <div class="col-md-3">
        <select class="form-control " name="{{field.name}}">
            {% for k ,v in field.extra|parse_config_attr %}
            <option value="{{k}}" {% if data[field.name] == k%} selected {%endif%}>{{v}}</option>
            {% endfor %}
        </select>
    </div>
    {% elif field.type == "radio" %}
    <div class="col-sm-10">
        {% for k ,v in field.extra|parse_config_attr %}
        <label class="radio-inline i-checks">
            <input type="radio" value="{{k}}" name="{{field.name}}" {% if data[field.name] == k%} checked {%endif%}><i></i> {{v}}
        </label>
        {% endfor %}
    </div>
    {% elif field.type == "checkbox" %}
    <div class="col-sm-10">
        {% for k ,v in field.extra|parse_config_attr %}
        <label class="checkbox-inline i-checks">
            <input type="checkbox" value="{{k}}" name="{{field.name}}" {% if data[field.name]|check_document_position(k)%} checked {%endif%}><i></i> {{v}}
        </label>
        {% endfor %}
    </div>
    {% elif field.type == "editor" %}
    <H5 class="col-sm-12 ">{{field.title}} {% if field.remark%}<span class="m-b-none text-muted"><i class="fa fa-info-circle text-info"></i> {{field.remark|safe}}</span> {%endif%}</H5>
    <div class="col-sm-12" >
        {%if editor == '1'%}
        {{HOOKS@adminEdit@1[field.name]|safe}}
        {%elif editor == '2_1'%}
        {{HOOKS@adminEdit@2_1[field.name]|safe}}
        {%elif editor == '2_2'%}
        {{HOOKS@adminEdit@2_2[field.name]|safe}}
        {%elif editor == '3'%}
        {{HOOKS@adminEdit@3[field.name]|safe}}
        {%else%}
        {{HOOKS@adminEdit[field.name]|safe}}
        {%endif%}
    </div>
    {% elif field.type == "picture" %}
    <div class="col-sm-10">
        {{HOOKS@adminUpPic[field.name]|safe}}
        </div>
    {% elif field.type == "file" %}
                                                        <div class="col-md-10">{{HOOKS@adminUpFile[field.name]|safe}}</div>
   {# <div class="col-md-10">
        <input id="pickfilesid" type="hidden" name="{{field.name}}" value="{{data[field['name']]}}"/>
        {%if config.ext.qiniu.is == 1%}

        <div id="container" style="{%if data[field['name']]%}display:none{%else%}display: block{%endif%}">
            <a class="btn btn-default " id="pickfiles" href="#" >
                <i class="glyphicon glyphicon-plus"></i>
                <span>选择文件</span>
            </a>
        </div>
        <div style="display:none" id="success" >
            <div class="alert-success">
                队列全部文件处理完毕
            </div>
        </div>
        <div >
            <table id="filetable" class="table table-striped table-hover text-left" data-id=""   style="margin-top:10px;{%if data[field['name']]%}display:block{%else%}display: none{%endif%}">
                <thead>
                <tr>
                    <th class="col-md-4">文件</th>
                    <th class="col-md-2">大小</th>
                    <th class="col-md-6">详情 <a href="#" class="text-info pull-right" id="delfile">删除</a> </th>
                </tr>
                </thead>
                <tbody id="fsUploadProgress">
                {%if data[field['name']]%}
                <tr  class="progressContainer" style="opacity: 1;">
                    <td class="progressName">{{data[field['name']]|get_file('name',false)}}<div class="Wrapper default"><div class="imgWrapper col-md-3"><img src="/static/admin/js/qiniu/default.png"></div></div></td>
                    <td class="progressFileSize">{{data[field['name']]|get_file('size',false)}} kb</td>
                    <td><div class="info"><div class=""><div><strong>Link:</strong><a target="_blank" href="{{data[field['name']]|get_file('savename',true)}}"> {{data[field['name']]|get_file('savename',true)}}</a></div>
                        <div class="hash"><strong>Hash:</strong>{{data[field['name']]|get_file('sha1',false)}}</div></div>
                       </div></td></tr>
                {%endif%}
                </tbody>
            </table>
        </div>
        {%else%}
        <!--用来存放文件信息-->
        <div id="thelist_{{field.name}}" class="uploader-list">
       {%if data[field['name']]%}

            <div id="thelist_file_id" class="uploader-list">
                <div id="WU_FILE_0" class="alert alert-info">
                    <button data-dismiss="alert" class="close remove-this" type="button">×</button>
                    <h4 class="info">{{data[field['name']]|get_file('name',false)}}</h4><p class="state">文件大小:{{data[field['name']]|get_file('size',false)}} kb</p></div>
            </div>
            {%endif%}
        </div>
        <div class="btns">

            <div id="picker_{{field.name}}" class="picker">选择文件</div>
            <a id="ctlBtn_{{field.name}}" class="btn btn-default">开始上传</a>
        </div>
        <script type="text/javascript">
            jQuery(function() {
                var $ = jQuery,
                        $list_{{field.name}} = $('#thelist_{{field.name}}'),
                        $btn_{{field.name}} = $('#ctlBtn_{{field.name}}'),
                        state = 'pending',
                        uploader_{{field.name}};

                uploader_{{field.name}} = WebUploader.create({

                    // 不压缩image
                    resize: false,

                    // swf文件路径
                    swf:'/static/admin/js/webuploader/Uploader.swf',

                    // 文件接收服务端。
                    server: '/admin/file/upload',

                    // 选择文件的按钮。可选。
                    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                    pick: {
                        id:'#picker_{{field.name}}',
                        multiple: false
                    },
                    fileNumLimit:1
                });
               
                // 当有文件添加进来的时候
                uploader_{{field.name}}.on( 'fileQueued', function( file ) {

                    $list_{{field.name}}.html( '<div id="' + file.id + '" class="alert alert-info">' +
                            ' <button data-dismiss="alert" class="close remove-this" type="button">×</button>'+
                            '<h4 class="info">' + file.name + '</h4>' +
                            '<p class="state">等待上传...</p>' +
                            '</div>' );
                        var $li_{{field.name}} = $( '#'+file.id );
                            $li_{{field.name}}.on('click', '.remove-this', function() {
                                uploader_{{field.name}}.removeFile( file.id );
//                                                                                 $list_{{field.name}}.html("");
                            })

                });

                // 文件上传过程中创建进度条实时显示。
                uploader_{{field.name}}.on( 'uploadProgress', function( file, percentage ) {
                    var $li_{{field.name}} = $( '#'+file.id ),
                            $percent_{{field.name}} = $li_{{field.name}}.find('.progress .progress-bar');

                    // 避免重复创建
                    if ( !$percent_{{field.name}}.length ) {
                        $percent_{{field.name}} = $('<div class="progress progress-striped active">' +
                                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                                '</div>' +
                                '</div>').appendTo( $li_{{field.name}} ).find('.progress-bar');
                    }

                    $li_{{field.name}}.find('p.state').text('上传中');

                    $percent_{{field.name}}.css( 'width', percentage * 100 + '%' );
                });

                uploader_{{field.name}}.on( 'uploadSuccess', function( file,res ) {
                    var name = "{{field.name}}";
                    $("input[name="+name+"]").val(res.id);
                    $( '#'+file.id ).find('p.state').text('已上传,文件大小:'+res.size);
                });

                uploader_{{field.name}}.on( 'uploadError', function( file ) {
                    $( '#'+file.id ).find('p.state').text('上传出错');
                });

                uploader_{{field.name}}.on( 'uploadComplete', function( file ) {
                    $( '#'+file.id ).find('.progress').fadeOut();
                });

                uploader_{{field.name}}.on( 'all', function( type ) {
                    if ( type === 'startUpload' ) {
                        state = 'uploading';
                    } else if ( type === 'stopUpload' ) {
                        state = 'paused';
                    } else if ( type === 'uploadFinished' ) {
                        state = 'done';
                    }

                    if ( state === 'uploading' ) {
                        $btn_{{field.name}}.text('暂停上传');
                    } else {
                        $btn_{{field.name}}.text('开始上传');
                    }
                });

                $btn_{{field.name}}.on( 'click', function() {
                    if ( state === 'uploading' ) {
                        uploader_{{field.name}}.stop();
                    } else {
                        uploader_{{field.name}}.upload();
                    }
                });
            });

        </script>
        {%endif%}
    </div>#}
                        {% else %}
                        <div class="col-md-2">
                            <input type="text" class="form-control  " name="{{field.name}}" value="{{data[field['name']]}}" >
                        </div>
                        {% endif %}

                        {% if field.remark and field.type != "editor"%}
                        <div class="col-md-12">
                            <span class="help-block m-b-none text-muted"><i class="fa fa-info-circle text-info"></i> {{field.remark|safe}}</span>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endif %}
            <div class="line line-dashed b-b line-lg pull-in"></div>
            {% endfor%}</div>
        {% endfor %}
    </div>

                                        <div class="form-group form-submit">
                                            <div class="col-sm-4 col-sm-offset-2">
                                                <button class="btn btn-primary btn-s-md ajax-post" type="submit" target-form="form-horizontal">确定</button>
                                                <button class="btn btn-default" onclick="javascript:history.back(-1);return false;" type="submit">返回</button>
                                                <input type="hidden" name="id" value="{{data.id}}"/>
                                                <input type="hidden" name="pid" value="{{data.pid}}"/>
                                                <input type="hidden" name="topid" value="{{data.topid}}"/>
                                                <input type="hidden" name="model_id" value="{{data.model_id}}"/>
                                                <input type="hidden" name="userid" value="{{userinfo.uid}}"/>
                                                <input type="hidden" name="category_id" value="{{data.category_id}}">
                                                <input type="hidden" name="backurl" value="{{ctx.referer()}}">
                                            </div>
                                        </div>
                                        </form>
                                </div>
                            </section></div>
                            <div class="col-lg-2 hide">
                               left
                                  </div>
                        </div>
                    </section>
                </section>
            </section>
        </section>
    </section>

</section>


{% endblock %}

{% block script %}
<script src="/static/admin/js/zTree/jquery.ztree.core-3.5.min.js" type="text/javascript"></script>
<script src="/static/admin/js/datepicker/bootstrap-datetimepicker.min.js" type="text/javascript"></script>
<script src="/static/admin/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js" type="text/javascript"></script>

<script src="/static/admin/js/parsley/parsley.min.js"></script>
<script src="/static/admin/js/parsley/parsley.extend.js"></script>
<script src="/static/admin/js/chosen/chosen.jquery.min.js"></script>
<script src="/static/admin/js/jQuery-Tags-Input/src/jquery.tagsinput.js"></script>
<script src="/static/admin/js/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>
<script type="text/javascript">
    <!--
    var zTree;
    var demoIframe;

    var setting = {
        async: {
            enable: true,
            url: "/admin/article/getmenu",
            otherParam: ["action", "add"]
        },
        view: {
            showLine: true,
            selectedMulti: false,
        },
        callback: {
            onAsyncSuccess: zTreeOnAsyncSuccess
        }
    };
    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        //console.log(treeNode)
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        treeObj.expandAll(true);
        var id= $("#"+treeId).attr("data-cate");
        curMenu = treeObj.getNodeByParam("id", id, null);
        console.log(treeId)
        treeObj.selectNode(curMenu);
    };
    function expandNode(e) {
        var zTree = $.fn.zTree.getZTreeObj("tree"),
                type = e.data.type,
                nodes = zTree.getSelectedNodes();
        if (type == "expandAll") {
            zTree.expandAll(true);
        } else if (type == "collapseAll") {
            zTree.expandAll(false);
        }
    }


    //-->
    $(function(){
        var t = $("#tree");
        t = $.fn.zTree.init(t, setting).expandAll(true);
        $("#expandAllBtn").bind("click", {type:"expandAll"}, expandNode);
        $("#collapseAllBtn").bind("click", {type:"collapseAll"}, expandNode);
        $('.date').datetimepicker({
            format: 'yyyy-mm-dd',
            language:"zh-CN",
            minView:2,
            autoclose:true
        });
        $('.time').datetimepicker({
            format: 'yyyy-mm-dd hh:ii',
            language:"zh-CN",
            minView:2,
            autoclose:true
        });


    })
</script>
{% endblock %}}